import 'dart:convert';

import 'package:client_flutter_android/bean/cabinet.dart';
import 'package:client_flutter_android/door_model.dart';
import 'package:client_flutter_android/vars.dart';
import 'package:client_flutter_android/widgets/btn.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:client_flutter_android/widgets/box.dart' as box_widget;

void main() {
  // runApp(const MyApp());
  runApp(ChangeNotifierProvider(
    create: (context) => DoorModel(),
    child: const MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final TextEditingController _controller = TextEditingController(text: '');
  late int len;
  String _msg = "";

  //浏览器
  WebViewController controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..addJavaScriptChannel(
      'ToFlutter',
      onMessageReceived: (JavaScriptMessage message) {
        print(message.message);
        dynamic result = jsonDecode(message.message);
        Provider.of<DoorModel>(Vars.navigatorKey.currentContext!, listen: false)
            .setBox(result["id"], result["czh"], result["occupied"]);
      },
    )
    ..loadRequest(Uri.parse('${Vars.doorUrl}/lightmini.html'));

  @override
  void initState() {
    super.initState();
    _controller.addListener(() async {
      //100个柜子：1号就是001,几十个柜子1号就是01
      // final permanentLength = Door.openDoors.length.toString().length;

      if (_controller.text.length != 4) return;
      var boxs = Provider.of<DoorModel>(context, listen: false).boxs;
      Cabinet? czhNotEmpty; //匹配车组的柜子
      Cabinet? czh2; //匹配车组的柜子

      // Cabinet? czhEmpty; //第一个空柜子

      for (var i = 0; i < boxs.length; i++) {
        // if (czhEmpty == null && boxs[i].czh == '') {
        //   czhEmpty = boxs[i];
        // }
        if (czhNotEmpty == null && boxs[i].czh == _controller.text) {
          czhNotEmpty = boxs[i];
        }
        if (czhNotEmpty != null && boxs[i].czh == _controller.text) {
          czh2 = boxs[i];
        }

      }

      //匹配车组的柜子开门
      if (czhNotEmpty != null) {
        try {
          if(czh2!=null){
            AlertDialog alert = AlertDialog(
              title: const Text('车型确认'),
              content: Text('请选择要打开柜门的车组${_controller.text}的车型！！！'),
              actions: <Widget>[
                // 取消按钮
                TextButton(
                  onPressed: () async {
                    Navigator.of(context).pop(); // 关闭对话框
                    controller.runJavaScript("openDoor(${jsonEncode((czhNotEmpty!.is400AF)?czh2:czhNotEmpty)})");
                    setState(() {
                      _msg = "${czhNotEmpty!.id} 号柜门已打开";
                    });
                  },
                  child: const Text('普通没S'),
                ),
                // 确认按钮
                TextButton(
                  onPressed: () async {
                    Navigator.of(context).pop(); // 关闭对话框
                    controller.runJavaScript("openDoor(${jsonEncode((czhNotEmpty!.is400AF)?czhNotEmpty:czh2)})");
                    setState(() {
                      _msg = "${czhNotEmpty!.id} 号柜门已打开";
                    });
                  },
                  child: const Text('智能S'),
                ),
              ],
            );
            // 显示对话框
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return alert;
              },
            );
          }else{
            //开门
            controller.runJavaScript("openDoor(${jsonEncode(czhNotEmpty)})");
            setState(() {
              _msg = "${czhNotEmpty!.id} 号柜门已打开";
            });
          }

        } catch (e) {
          debugPrint(e.toString());
          setState(() {
            _msg = "输入的车组号 ${_controller.text} 打开失败，异常：${e.toString()}";
          });
        }
      } else {
        setState(() {
          _msg = "输入的车组号 ${_controller.text} 不存在";
        });
      }

      _controller.text = '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        navigatorKey: Vars.navigatorKey,
        debugShowCheckedModeBanner: false,
        home: SafeArea(
          child: Scaffold(
            body: Column(
              children: [
                Expanded(
                  flex: 1,
                  child: MyHomePage(
                    controller: controller,
                  ),
                ),
                Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                  Expanded(
                    flex: 1,
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
                      child: TextField(
                        enabled: false,
                        style:  TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 30,
                          color:  const Color.fromARGB(255,13,110,253).withAlpha(30),
                        ),
                        // textAlign: TextAlign.center,
                        controller: _controller,
                        decoration: InputDecoration(
                          hintText: "输入要打开柜门的 车组号 ",
                          helperText: _msg,
                          helperStyle: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 30,
                              
                              color: _msg.contains("已打开")
                                  ? Colors.green
                                  : Colors.red),
                          border: const OutlineInputBorder(),
                        ),
                      ),
                    ),
                  ),
                  Column(
                    children: [
                      Btn(
                        width: 90,
                        height: 90,
                        title: '1',
                        onTap: () {
                          _controller.text = '${_controller.text}1';
                        },
                        onTagTap: () {},
                      ),
                      Btn(
                        width: 90,
                        height: 90,
                        title: '4',
                        onTap: () {
                          _controller.text = '${_controller.text}4';
                        },
                        onTagTap: () {},
                      ),
                      Btn(
                        width: 90,
                        height: 90,
                        title: '7',
                        onTap: () {
                          _controller.text = '${_controller.text}7';
                        },
                        onTagTap: () {},
                      ),
                    ],
                  ),
                  Column(
                    children: [
                      Btn(
                        width: 90,
                        height: 90,
                        title: '2',
                        onTap: () {
                          _controller.text = '${_controller.text}2';
                        },
                        onTagTap: () {},
                      ),
                      Btn(
                        width: 90,
                        height: 90,
                        title: '5',
                        onTap: () {
                          _controller.text = '${_controller.text}5';
                        },
                        onTagTap: () {},
                      ),
                      Btn(
                        width: 90,
                        height: 90,
                        title: '8',
                        onTap: () {
                          _controller.text = '${_controller.text}8';
                        },
                        onTagTap: () {},
                      ),
                    ],
                  ),
                  Column(
                    children: [
                      Btn(
                        width: 90,
                        height: 90,
                        title: '3',
                        onTap: () {
                          _controller.text = '${_controller.text}3';
                        },
                        onTagTap: () {},
                      ),
                      Btn(
                        width: 90,
                        height: 90,
                        title: '6',
                        onTap: () {
                          _controller.text = '${_controller.text}6';
                        },
                        onTagTap: () {},
                      ),
                      Btn(
                        width: 90,
                        height: 90,
                        title: '9',
                        onTap: () {
                          _controller.text = '${_controller.text}9';
                        },
                        onTagTap: () {},
                      ),
                    ],
                  ),
                  Column(
                    children: [
                      Btn(
                        width: 90,
                        height: 90,
                        title: '清',
                        onTap: () {
                          _controller.text = '';
                        },
                        onTagTap: () {},
                      ),
                      Btn(
                        width: 90,
                        height: 90,
                        title: '删',
                        onTap: () {
                          if (_controller.text.isEmpty) {
                            return;
                          }
                          _controller.text = _controller.text
                              .substring(0, _controller.text.length - 1);
                        },
                        onTagTap: () {},
                      ),
                      Btn(
                        width: 90,
                        height: 90,
                        title: '0',
                        onTap: () {
                          _controller.text = '${_controller.text}0';
                        },
                        onTagTap: () {},
                      ),
                    ],
                  ),
                ]),
                Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                  IconButton(
                      tooltip: '腰包已领取',
                      onPressed: () {},
                      icon: const Icon(
                        Icons.local_offer,
                        color: Colors.red,
                      )),
                  const Text('腰包已领取'),
                  IconButton(
                      tooltip: '腰包未领取',
                      onPressed: () {},
                      icon: const Icon(
                        Icons.local_offer,
                        color: Colors.green,
                      )),
                  const Text('腰包未领取'),
                  IconButton(
                      tooltip: '空柜',
                      onPressed: () {},
                      icon: const Icon(
                        Icons.local_offer,
                        color: Colors.grey,
                      )),
                  const Text('空柜'),
                ])
              ],
            ),
          ),
        ));
  }
}

class MyHomePage extends StatefulWidget {
  final WebViewController controller;
  const MyHomePage({
    super.key,
    required this.controller,
  });

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //数据
  late List<Widget> genalRows = [];
  Future<Widget> loadBox(BuildContext context) async {
    genalRows = [];
    // List<Cabinet> boxs = await Box.getBoxs();
    List<Cabinet> boxs = Provider.of<DoorModel>(context).boxs;

    // print(boxs.length);

    int count = 0;
    int colsCount = (boxs.length / 7).ceil();

    for (int col = 0; col < colsCount; col++) {
      List<Widget> genalCols = [];
      for (int row = 0; row < 7; row++) {
        count++;
        if (count == 23 || count == 24) {
          genalCols.add(box_widget.Box(index: count));
        } else {
          if (count > 23) {
            if (count - 3 < boxs.length) {
              genalCols.add(box_widget.Box(
                  index: count,
                  cabinet: boxs[count - 3],
                  controller: widget.controller));
            }
          } else {
            genalCols.add(box_widget.Box(
                index: count,
                cabinet: boxs[count - 1],
                controller: widget.controller));
          }
        }
      }
      genalRows.add(Column(
        children: genalCols,
      ));
    }

    return Scrollbar(
      child: SingleChildScrollView(
          primary: true,
          scrollDirection: Axis.horizontal,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: genalRows,
          )),
    );
  }

  @override
  Widget build(BuildContext context) {
    // SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    return FutureBuilder(
      future: loadBox(context),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const CircularProgressIndicator();
        }
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return const Text('Error');
          }
        }
        return snapshot.data!;
      },
    );
  }
}
